import { message } from "@/utils/message";
import { getTaskList, create, del, getTaskShow } from "@/api/taskApi";
import { reactive, ref, onMounted, toRaw, h } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import info from "../info.vue";
import editForm from "../form/index.vue";
import type { FormItemProps } from "../utils/types";
export function useRole() {
  const form = reactive({
    username: "",
    page: 1,
    perPage: 10
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const getTaskType = (type, text = false) => {
    switch (type) {
      case 1:
        return text ? "入库任务" : "warning";
      case 2:
        return text ? "出库任务" : "danger";
      case 4:
        return text ? "同层移库" : "primary";
    }
  };
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "taskId"
    },
    // {
    //   label: "任务分类",
    //   prop: "moduleCode"
    // },
    {
      label: "任务类型",
      prop: "taskTypeStr",
      // cellRenderer: ({ row, props }) => (
      //   <el-tag
      //     size={props.size}
      //     type={getTaskType(row.taskType)}
      //     effect="plain"
      //   >
      //     {getTaskType(row.taskType, true)}
      //   </el-tag>
      // )
    },
    {
      label: "任务号",
      prop: "taskNo"
    },
    {
      label: "取货位",
      prop: "startPos"
    },
    {
      label: "放货位",
      prop: "endPos"
    },
    {
      label: "任务状态",
      prop: "taskStatusStr"
    },
    {
      label: "创建时间",
      prop: "createdAt"
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];

  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getTaskList(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = 1;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getTaskList(toRaw(form)).then(result => {
      dataList.value = result.result.list;
      pagination.total = result.result.total;
      pagination.pageSize = result.result.per_page;
      pagination.currentPage = result.result.current_page;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }
  async function onSearch() {
    loading.value = true;
    const { result } = await getTaskList(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.per_page;
    pagination.currentPage = result.current_page;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  //详情
  const formRef = ref();
  function handleDelete(row) {
    del({ taskId: row.taskId }).then(result => {
      if (result.code == 200) {
        message(`删除成功`, { type: "success" });
        onSearch();
      } else {
        message(`删除失败`, { type: "error" });
      }
    });
  }
  async function onDetail(row) {
	// const res = await getTaskShow({ wcsTaskId: row.wcsTaskId });
	// if(res.code !== 200) {
	// 	message(res.msg ?? "操作失败,请联系管理员", {
	// 	  type: "error"
	// 	});
	// 	return
	// }
    addDialog({
      title: `任务详情`,
      props: {
        formInline: {
          createdAt: row?.createdAt ?? "",
          endPos: row?.endPos ?? "",
          errorMsg: row?.errorMsg ?? "",
          feedbackUrl: row?.feedbackUrl ?? "",
          moduleCode: row?.moduleCode ?? "",
          moveObj: row?.moveObj ?? "",
          taskId: row?.taskId ?? "",
          taskStatus: row?.taskStatus ?? "",
          taskType: row?.taskType ?? "",
          updatedAt: row?.updatedAt ?? ""
        }
      },
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(info)
    });
  }
  async function openDialog(title = "新增", row?: FormItemProps) {
    let formInline = {};
    if (`${title}` == "新增") {
      formInline = {
        title: "新增",
      };
    } else {
	  const res = await getTaskShow({ taskId: row.taskId });
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      formInline = {
        title: "修改",
        taskStatus: row?.taskStatus ?? "",
        moduleCode: row?.moduleCode ?? "",
        taskType: row?.taskType ?? "",
        endPos: row?.endPos ?? "",
		startPos: row?.startPos ?? "",
		taskNo: row?.taskNo ?? "",
        moveObj: row?.moveObj ?? "",
        taskId: row?.taskId ?? "",
        errorMsg: row?.errorMsg ?? "",
        feedbackUrl: row?.feedbackUrl ?? ""
      };
    }
    addDialog({
      title: `${title}任务`,
      props: {
        formInline: formInline
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`${title}信息`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              create(curData).then(result => {
                if (result.code === 200) {
                  chores();
                } else {
                  message(result.msg, { type: "error" });
                }
              });
            } else {
              edit(curData).then(result => {
                if (result.code === 20) {
                  chores();
                } else {
                  message(`修改失败`, { type: "error" });
                }
              });
            }
          }
        });
      }
    });
  }
  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    handleSizeChange,
    handleCurrentChange,
    /** 详情 */
    onDetail,
    /** 新增 修改 */
    openDialog,
    handleDelete
  };
}
